<template>
  <div class="test-container">
    <van-pull-refresh
      v-model="refreshing"
      @refresh="onRefresh"
      class="refresh-container"
    >
      <van-list
        class="list-container"
        v-model:loading="loading"
        :finished="finished"
        finished-text="没有更多了"
        :immediate-check="false"
        @load="onLoad"
      >
        <template v-if="table && table.length > 0">
          <van-cell-group
            v-for="item in table"
            :key="item.id"
            inset
            class="exam-card"
          >
            <van-cell title="考试信息" size="large" />
            <div class="exam-info">
              <div class="info-row">
                <span>试卷标题：{{ item.title }}</span>
              </div>
              <div class="info-row">
                <span>题目数量：{{ item.number }}</span>
              </div>
              <div class="info-row">
                <span>考试科目：{{ getSubjectName(item.subjectId) }}</span>
              </div>
              <div class="info-row">
                <span>考试时间：{{ item.testTime / 60 }}分钟</span>
              </div>
              <div class="info-row">
                <span>创建人：{{ item.userName }}</span>
              </div>
              <div class="info-row">
                <span>创建时间：{{ item.createTime }}</span>
              </div>
              <div class="info-row">
                <span>过期时间：{{ item.expiredTime }}</span>
              </div>
              <van-button
                type="primary"
                block
                class="start-exam-button"
                @click="startExam(item)"
              >
                <van-icon name="edit" /> 开始考试
              </van-button>
            </div>
          </van-cell-group>
        </template>

        <van-empty v-if="table.length === 0 && !loading" description="暂无试卷">
          <template #description>
            <span v-if="getToken()" style="color: #969799">没有试卷</span>
            <to-login v-else />
          </template>
        </van-empty>
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive, nextTick, onUnmounted } from "vue";
import router from "@/router";
import { useStore } from "vuex";
import questionItemApi from "@/api/questionItem/questionItem";
import subjectApi from "@/api/subject/index";
import ToLogin from "@/components/toLogin.vue";
import { getToken } from "@/utils/auth";
import { emitter } from "@/utils/bus";
import { showLoadingToast } from "vant";
import NProgress from "nprogress";
import "nprogress/nprogress.css";

const table = ref([]);
const store = useStore();
const loading = ref(false);
const finished = ref(false);
const refreshing = ref(false);
const totalCount = ref(0);

const form = reactive({
  title: "",
});
const currentPage = ref(1);
const pageSize = ref(10);
const subjects = ref([]);

// 配置 NProgress
NProgress.configure({
  easing: "ease",
  speed: 500,
  showSpinner: false, // 不显示加载圆圈
  trickleSpeed: 200,
  minimum: 0.3,
});

// 上拉加载更多
const onLoad = async () => {
  console.log("触发加载更多");
  if (loading.value) return;

  try {
    loading.value = true;
    await loadData(currentPage.value);
    currentPage.value += 1;

    // 添加延迟，确保UI更新后再检查是否加载完成
    await nextTick();

    if (table.value.length >= totalCount.value) {
      finished.value = true;
    }

    loading.value = false;
  } catch (error) {
    console.error("加载数据失败:", error);
    loading.value = false;
  }
};

// 下拉刷新
const onRefresh = async () => {
  try {
    finished.value = false;
    currentPage.value = 1;
    table.value = [];

    await loadData(currentPage.value);
    currentPage.value += 1;

    if (table.value.length >= totalCount.value) {
      finished.value = true;
    }

    refreshing.value = false;
  } catch (error) {
    console.error("刷新数据失败:", error);
    refreshing.value = false;
  }
};

const loadData = async (page) => {
  const res = await questionItemApi.selectQuestionItems(
    form.title,
    page,
    pageSize.value
  );

  totalCount.value = res.data.total || 0;

  if (refreshing.value) {
    table.value = [];
  }

  if (res.data.records && res.data.records.length > 0) {
    table.value.push(...res.data.records);
  }

  if (
    !res.data.records ||
    res.data.records.length === 0 ||
    table.value.length >= totalCount.value
  ) {
    finished.value = true;
  } else {
    finished.value = false;
  }
};

const getSubject = async () => {
  const res = await subjectApi.getAll();
  subjects.value = res.data;
};

const getSubjectName = (subjectId) => {
  const subject = subjects.value.find((s) => s.id === subjectId);
  return subject ? subject.name : "未知科目";
};

const startExam = (item) => {
  NProgress.start(); // 开始显示进度条

  router
    .push({
      path: `/test/startTest`,
      query: { questionItemId: item.id, title: item.title },
    })
    .finally(() => {
      NProgress.done(); // 完成进度条
    });
};

// 添加事件监听
const handleMessage = () => {
  currentPage.value = 1;
  table.value = [];
  loadData(currentPage.value);
};

onMounted(async () => {
  if (getToken()) {
    await getSubject();

    // 添加事件监听
    emitter.on("updateExamList", handleMessage);

    setTimeout(async () => {
      currentPage.value = 1;
      loading.value = true;
      await loadData(currentPage.value);
      currentPage.value += 1;

      if (table.value.length >= totalCount.value) {
        finished.value = true;
      }

      loading.value = false;
    }, 100);
  }
});

// 添加清理事件监听
onUnmounted(() => {
  emitter.off("updateExamList", handleMessage);
});
</script>

<style scoped>
.test-container {
  display: flex;
  flex-direction: column;
  box-sizing: border-box;
  align-items: center;
  overflow: auto;
}

.list-container {
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.refresh-container {
  height: 95%;
  width: 100%;
  overflow-y: auto;
  overflow-x: hidden;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.exam-card {
  margin-bottom: 16px;
  width: 100%;
  max-width: 600px;
}

.exam-info {
  padding: 8px 16px 16px;
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

.info-row {
  margin-bottom: 8px;
  font-size: 14px;
  line-height: 1.5;
  word-break: break-all;
}

.start-exam-button {
  margin-top: 16px;
  background: linear-gradient(to right, #6ea5e8, #1677ff) !important;
  border: none !important;
}

.start-exam-button:active {
  opacity: 0.9;
}

/* 自定义进度条样式 */
#nprogress .bar {
  background: #4096ff !important; /* 进度条颜色 */
  height: 3px !important; /* 进度条高度 */
}

/* 去掉进度条的边缘发光效果 */
#nprogress .peg {
  box-shadow: none !important;
}
</style>
